<template>
    <div ref="chart" style="width: 100%; height: 450px; top: 20px; left: 10px;"></div>
  </template>
  
  <script>
  import * as echarts from "echarts";
  
  export default {
    name: "DynamicSortingChart",
    data() {
      return {
        apiUrl: "/api/queryAllStockRegion", // API 地址
        chart: null,
      };
    },
    mounted() {
      this.initChart();
    },
    methods: {
      // 获取数据并按时间排序
      async fetchData() {
        try {
          const response = await fetch(this.apiUrl);
          const result = await response.json();
          if (result.code === "200") {
            return result.data;
          } else {
            console.error("API返回错误:", result.msg);
            return [];
          }
        } catch (error) {
          console.error("数据请求失败：", error);
          return [];
        }
      },
      // 初始化图表
      async initChart() {
        const rawData = await this.fetchData();
  
        // 按年份分组
        const groupedData = {};
        rawData.forEach((item) => {
          if (!groupedData[item.year]) {
            groupedData[item.year] = [];
          }
          groupedData[item.year].push({ region: item.region, value: item.value });
        });
  
        // 按数值排序并限制为前6项
        const years = Object.keys(groupedData).sort(); // 按时间排序
        const formattedData = years.map((year) => ({
          year,
          data: groupedData[year]
            .sort((a, b) => b.value - a.value)
            .slice(0, 7),
        }));
  
        // 动态生成图表
        this.chart = echarts.init(this.$refs.chart);
        let currentIndex = 0;
  
        const option = {
          title: {
            text: "各国产量数据",
            left: "center",
            top: 15,
            textStyle: {
              color: "#FFFFFF", // 标题颜色设置为白色
              fontSize: 20,
              fontFamily: "YouYuan",
            },
          },
          xAxis: {
            type: "value",
            boundaryGap: [0, 0.1],
            axisLabel: {
              textStyle: {
                color: '#FFFFFF' // y轴标签颜色设置为白色
              }
            }
          },
          yAxis: {
            type: "category",
            data: [], // 动态填充
            inverse: true, // 倒序显示
            axisLabel: {
              textStyle: {
                color: '#FFFFFF' // y轴标签颜色设置为白色
              }
            }
          },
          tooltip: {
            trigger: "item",
            formatter: "{b} : {c}",
          },
          series: [
            {
              type: "bar",
              data: [], // 动态填充
              label: {
                show: true,
                position: "right",
                formatter: "{c}",
                color: "#FFFFFF", // 白色标签文字
              },
              itemStyle: {
                color: (params) => {
                  const colors = [
                    "#ffffd2",
                    "#fcbad3",
                    "#aa96da",
                    "#a8d8ea",
                    "#71c9ce",
                    "#a6e3e9",
                    "#cbf1f5",
                    "#e3fdfd",
                  ];
                  return colors[params.dataIndex % colors.length];
                },
                borderRadius: [0, 10, 10, 0], // 右上、右下圆角
                shadowColor: "rgba(0, 0, 0, 0.3)", // 阴影颜色
                shadowBlur: 10, // 阴影模糊半径
                shadowOffsetX: 3, // 阴影横向偏移
                shadowOffsetY: 3, // 阴影纵向偏移
              },
              emphasis: {
                itemStyle: {
                  borderRadius: [0, 10, 10, 0], // 高亮时同样保留圆角
                },
              },
            },
          ],
          animationDuration: 1000,
          animationDurationUpdate: 1000,
          graphic: {
            elements: [
              {
                type: "text",
                right: 10,
                bottom: 10,
                style: {
                  text: "",
                  font: "bold 40px sans-serif",
                  fill: "rgba(255, 255, 255, 0.3)",
                },
                z: 100,
              },
            ],
          },
        };
  
        const updateChart = () => {
          const { year, data } = formattedData[currentIndex];
  
          this.chart.setOption({
            yAxis: {
              data: data.map((item) => item.region),
            },
            series: [
              {
                data: data.map((item) => item.value),
              },
            ],
            graphic: {
              elements: [
                {
                  type: "text",
                  right: 80,
                  bottom: 100,
                  style: {
                    text: year.toString(),
                  },
                },
              ],
            },
          });
  
          currentIndex = (currentIndex + 1) % formattedData.length;
        };
  
        // 初始化图表
        this.chart.setOption(option);
        updateChart();
  
        // 定时更新
        setInterval(updateChart, 2000);
  
        // 自适应调整
        window.addEventListener("resize", () => {
          if (this.chart) {
            this.chart.resize();
          }
        });
      },
    },
  };
  </script>
  
  <style scoped>
  /* 无背景和额外样式 */
  </style>
  